layui.define(
  [
    "laydate",
    "table",
    "laypage",
    "form",
    "element",
    "layer",
    "transfer",
    "util",
  ],
  function (exports) {
    var laydate = layui.laydate,
      laypage = layui.laypage,
      layer = layui.layer,
      element = layui.element,
      form = layui.form,
      loadIndex = "",
      table = layui.table,
      transfer = layui.transfer,
      util = layui.util;
    //日期范围
    laydate.render({
      elem: "#monthRange",
      type: "month",
      range: ["#monthRangeStart", "#monthRangeEnd"],
    });
    form.on("submit(searchFolderBtn)", function (data) {
      var data = data.field;
      table.reload("projectManagementTable", {
        where: {
          sort: "1",
          startTime: data.startTime,
          endTime: data.endTime,
          projectName: data.projectName,
        },
      });
      renderProduct1(
        page,
        limit,
        data.startTime,
        data.endTime,
        data.projectName
      );
    });
    // 创建文件夹
    $(".createFolderBtn").on("click", function () {
      layer.open({
        title: '<i class="fa fa-plus"></i>&nbsp;新增文件夹',
        type: 1,
        area: ["30%", "28%"],
        shadeClose: true,
        // btn: ["确定", "取消"],
        // btnAlign: "c",
        content: $("#createFolderForm").html(),
        success: function (layero, index) {
          form.on("submit(createFolderSubmit)", function (d) {
            $.ajax({
              type: "POST",
              url: base_url + "/projectManage/createFolder",
              contentType: "application/json; charset=utf-8",
              async: true,
              data: JSON.stringify(d.field),
              dataType: "json",
              headers: {
                Accept: "application/json; charset=utf-8",
                Authorization: layui.sessionData("userToken").key,
              },
              success: function (res) {
                console.log(res);
              },
            });
          });
        },
      });
    }); //
    // $(".removeBtn").on("click", function () {
    //   layer.open({
    //     title: "项目列表",
    //     type: 1,
    //     fix: false,
    //     skin: "nextLevelFileSty",
    //     // 加上边框
    //     area: ["45%", "52%"],
    //     // 宽高
    //     content: $("#changeFile").html(),
    //     success: function (layero, index) {
    //       //  #flowDate;
    //       handleOneLevelList().then(({ oneLevelCount, oneLevelData }) => {
    //         oneLevelData.forEach((value, index) => {
    //           console.log(index);
    //         });
    //       });
    //     },
    //   });
    // });
    // 列表接口
    table.render({
      elem: "#projectManagementTable",
      skin: "nob",
      even: true,
      url: base_url + "/projectManage/queryProListByProperty",
      headers: {
        Accept: "application/json; charset=utf-8",
        Authorization: layui.sessionData("userToken").key,
      },
      method: "post",
      contentType: "application/json",
      cellMinWidth: 80,
      height: "full-120",
      parseData: function (res) {
        return {
          code: 0,
          count: res.data.projectList.total,
          data: res.data.projectList.list,
          msg: res.data.message || "请求成功",
        };
      },
      cols: [
        [
          {
            event: "projectFilesNext",
            templet:
              '<div class="filesIcon"><img  src="../../layuiadmin/images/filesIcon.png"></div>',
          },
          { field: "proNmae", title: "项目名称", align: "center" },
          { field: "userName", title: "创建者", align: "center" },
          { field: "date", title: "创建时间", align: "center" },
          { field: "date", title: "更新时间", align: "center" },
        ],
      ],
      page: true,
      limit: 5,
      limits: [5, 10, 15, 20, 25, 30],
      where: { sort: "1" },
      text: { none: "无数据" },
      done: function (res) {
        // 表格渲染完成之后的回调
        var that = this.elem.next();
        res.data.forEach(function (item, index) {
          if (index % 2 == 0) {
            var tr = that
              .find(".layui-table-box tbody tr[data-index='" + index + "']")
              .css("background-color", "transparent");
          } else {
            var tr = that
              .find(".layui-table-box tbody tr[data-index='" + index + "']")
              .css("background", "#EDF2FB");
          }
        });
      },
    });
    //监听行单击事件（双击事件为：rowDouble）
    table.on("row(projectManagementTable)", function (obj) {
      var data = obj.data;
      $(this).attr(
        "lay-href",
        "./pages/projectManagementNextT.html?proID=" +
          data.proID +
          "&proType=" +
          data.proType
      );
      // location.href =
      //   "projectManagementNextT.html?proID=" + proID + "&proType=" + proType;
    });
    var page = 1; //当前页
    var limit = 40; //每页显示的数目
    var resCount, resData;
    renderPage1();

    //渲染展示文件的html页面
    function renderProductHtml(data) {
      layer.close(loadIndex);
      var str = ""; //用来存储html内容
      if (data.length > 0) {
        $.each(data, function (v, o) {
          str += `<li class="nextLevelFile moveOtherFile" data-proID="${
            o.proID
          }" data-proType="${o.proType}"><a title="${
            o.proNmae
          }"><img src="../../layuiadmin/images/filesIcon.png"/><p class="changename">${
            o.proNmae ? o.proNmae : ""
          }</p></a></li>`;
        });

        $(".projectManagementList #projectManagementListCon").html(str);
      } else {
        $(".projectManagementList #projectManagementListCon").html(
          "无相关项目"
        );
      }
    }
    // 控制页面文件夹是否可以移动
    layui.sessionData("isMove", {
      key: "key",
      value: false,
    });
    $(".removeBtn").on("click", function () {
      if (layui.sessionData("isMove").key) {
        layui.sessionData("isMove", {
          key: "key",
          value: false,
        });
        $(this).addClass("layui-btn-primary");
      } else {
        layui.sessionData("isMove", {
          key: "key",
          value: true,
        });
        $(this).removeClass("layui-btn-primary");
        // // 下一级目录跳转
        // $(".nextLevelFile").on("click", function (event) {
        //   var proID = $(this).attr("data-proID"),
        //     proType = $(this).attr("data-proType");
        //   location.href =
        //     "projectManagementNextT.html?proID=" +
        //     proID +
        //     "&proType=" +
        //     proType;
        // });
      }
    });
    $(".moveOtherFile").on("click", function () {
      if (!layui.sessionData("isMove").key) {
        // return;
        var proID = $(this).attr("data-proID"),
          proType = $(this).attr("data-proType");
        location.href =
          "projectManagementNextT.html?proID=" + proID + "&proType=" + proType;
        // });
      }
      var proID = $(this).attr("data-proID");
      if (!$(this).hasClass("current")) {
        $(this).addClass("current");
        var otherLayer = layer.open({
          title: $(this).children("p").text(),
          type: 1,
          fix: false,
          resize: false,
          skin: "nextLevelFileSty",
          // 加上边框
          area: ["40%", "80%"],
          // 宽高
          content: $("#changeFile").html(),
          success: function (layero, index) {
            $.ajax({
              async: false,
              url: base_url + "/projectManage/selMoveFile",
              headers: {
                Accept: "application/json; charset=utf-8",
                Authorization: layui.sessionData("userToken").key,
              },
              method: "post",
              contentType: "application/json",
              data: JSON.stringify({
                proID: proID,
              }),
              dataType: "json",
              success: function (result) {
                if (result.code == "200") {
                  var moveData = result.data,
                    itemFileTitle = "",
                    itemFile = "";
                  var moveDataList = moveData["其他"];
                  if (moveDataList && moveDataList.length > 0) {
                    for (let item in moveDataList) {
                      itemFile +=
                        ' <dd data-id="' +
                        moveDataList[item].id +
                        '"><a href="javascript:;">' +
                        fileSuffixFun(moveDataList[item].fileName) +
                        moveDataList[item].fileName +
                        "</a></dd>";
                    }
                    itemFileTitle =
                      '<li class="layui-nav-item layui-nav-itemed"><a href="javascript:;"><img src="../../layuiadmin/images/filesIcon.png"/>其他</a><dl class="layui-nav-child">' +
                      itemFile +
                      "</dl></li>";
                    $(".projectFilesList .fileChangeBtn").show();
                  } else {
                    $(".projectFilesList .fileChangeBtn").hide();
                    itemFileTitle =
                      '<li class="layui-nav-item layui-nav-itemed"><a href="javascript:;"><img src="../../layuiadmin/images/filesIcon.png"/>其他</a><dl class="layui-nav-child"><dd style="font-size:14px;color:#999999;text-align:center;">空文件夹</dd></dl></li>';
                  }
                  function fileSuffixFun(item) {
                    if (item.indexOf(".doc") != -1) {
                      return '<img src="../../layuiadmin/images/word.png"/>';
                    } else if (item.indexOf(".jpg") != -1) {
                      return '<img src="../../layuiadmin/images/word.png"/>';
                    }
                  }
                  $(".otherFilesList").html(itemFileTitle);

                  var changeId = []; //所选中的文件id
                  $(".otherFilesList dd").on("click", function () {
                    var changeItem = $(this);
                    var changeItemId = changeItem.attr("data-id"); //当前文件id

                    if (changeItem.hasClass("changeFile")) {
                      let index = changeId.indexOf(changeItemId);
                      index > -1 && changeId.splice(index, 1);
                      console.log("removeClass", changeId);
                      changeItem.removeClass("changeFile");
                    } else {
                      console.log("addClass", changeId);
                      changeItem.addClass("changeFile");
                      changeId.push(changeItem.attr("data-id"));
                    }
                    console.log(changeId);
                  });
                  $(".fileChangeBtn").on("click", function () {
                    layer.closeAll();
                    filesAllListFun(changeId, proID);
                  });
                }
              },
            });
          },
        });
      } else {
        $(this).removeClass("current");
      }
    });

    function filesAllListFun(changeId, proID) {
      layer.open({
        title: "全部项目",
        type: 1,
        fix: false,
        resize: false,
        skin: "nextLevelFileSty",
        // 加上边框
        area: ["40%", "80%"],
        // 宽高
        content: $("#changeAllFile").html(),
        success: function (layero, index) {
          $.ajax({
            async: false,
            url: base_url + "/projectManage/selMovePro",
            headers: {
              Accept: "application/json; charset=utf-8",
              Authorization: layui.sessionData("userToken").key,
            },
            method: "post",
            contentType: "application/json",
            data: JSON.stringify({
              proID: proID,
            }),
            dataType: "json",
            success: function (result) {
              if (result.code == "200") {
                var filesAllData = result.data.proList,
                  itemFileTitle = "",
                  itemFile = "";
                filesAllData.forEach((item, index) => {
                  itemFile +=
                    '<li  data-id="' +
                    item.proID +
                    '" class="layui-nav-item layui-nav-itemed projectAllItem"><a href="javascript:;"><img src="../../layuiadmin/images/filesIcon.png"/>' +
                    item.proNmae +
                    "</a></li>";
                  $(".otherFilesList").html(itemFile);
                });
                $(".projectAllItem").on("click", function () {
                  var changeItem = $(this);
                  var changeItemId = changeItem.attr("data-id"); //当前文件id

                  if (changeItem.hasClass("changeFile")) {
                  } else {
                    projectAllChangeFun(changeId, changeItemId, $(this).text());
                    // layer.closeAll();
                  }
                });
              }
            },
          });
        },
      });
    }

    function projectAllChangeFun(changeId, changeItemId, projectName) {
      var otherLayer = layer.open({
        title: projectName,
        type: 1,
        fix: false,
        resize: false,
        skin: "nextLevelFileSty",
        // 加上边框
        area: ["40%", "80%"],
        // 宽高
        content: $("#changeFileNext").html(),
        success: function (layero, index) {
          $.ajax({
            async: false,
            url: base_url + "/projectManage/selMoveFile",
            headers: {
              Accept: "application/json; charset=utf-8",
              Authorization: layui.sessionData("userToken").key,
            },
            method: "post",
            contentType: "application/json",
            data: JSON.stringify({
              proID: changeItemId,
            }),
            dataType: "json",
            success: function (result) {
              if (result.code == "200") {
                var moveData = result.data,
                  itemFileTitle = "",
                  itemFile = "";
                var moveDataList = moveData["其他"];
                if (moveDataList && moveDataList.length > 0) {
                  for (let item in moveDataList) {
                    itemFile +=
                      ' <dd data-id="' +
                      moveDataList[item].id +
                      '"><a href="javascript:;">' +
                      fileSuffixFun(moveDataList[item].fileName) +
                      moveDataList[item].fileName +
                      "</a></dd>";
                  }
                  itemFileTitle =
                    '<li class="layui-nav-item layui-nav-itemed"><a href="javascript:;"><img src="../../layuiadmin/images/filesIcon.png"/>其他</a><dl class="layui-nav-child">' +
                    itemFile +
                    "</dl></li>";
                  $(".projectFilesList .fileChangeBtn").show();
                } else {
                  $(".projectFilesList .fileChangeBtn").hide();
                  itemFileTitle =
                    '<li class="layui-nav-item layui-nav-itemed"><a href="javascript:;"><img src="../../layuiadmin/images/filesIcon.png"/>其他</a><dl class="layui-nav-child"><dd style="font-size:14px;color:#999999;text-align:center;">空文件夹</dd></dl></li>';
                }
                function fileSuffixFun(item) {
                  if (item.indexOf(".doc") != -1) {
                    return '<img src="../../layuiadmin/images/word.png"/>';
                  } else if (item.indexOf(".jpg") != -1) {
                    return '<img src="../../layuiadmin/images/word.png"/>';
                  }
                }
                $(".otherFilesList").html(itemFileTitle);
                $(".fileOtherChangeBtn").on("click", function () {
                  $.ajax({
                    async: true,
                    url: base_url + "/projectManage/moveFolder",
                    headers: {
                      Accept: "application/json; charset=utf-8",
                      Authorization: layui.sessionData("userToken").key,
                    },
                    method: "post",
                    contentType: "application/json",
                    data: JSON.stringify({
                      proID: changeItemId,
                      moveFileID: changeId,
                    }),
                    dataType: "json",
                    success: function (result) {
                      if (result.code == "200") {
                        layer.msg(result.message, {
                          time: 1000,
                          icon: 6,
                          end: function () {
                            layer.closeAll();
                          },
                        });
                      } else {
                        layer.msg(result.message, { icon: 2 });
                      }
                    },
                  });
                  layer.close(otherLayer);
                });
              }
            },
          });
        },
      });
    }

    // 一级目录列表
    function handleOneLevelList(proID) {
      return new Promise((resolve, reject) => {
        $.ajax({
          async: false,
          url: base_url + "/projectManage/selMoveFile",
          headers: {
            Accept: "application/json; charset=utf-8",
            Authorization: layui.sessionData("userToken").key,
          },
          method: "post",
          contentType: "application/json",
          data: JSON.stringify({
            proID: proID,
          }),
          dataType: "json",
          success: function (result) {
            if (result.code == "200") {
              console.log(result);
              oneLevelCount = result.data.projectList.total;
              oneLevelData = result.data.projectList.list.length
                ? result.data.projectList.list
                : [];
              // console.log("一级列表", resCount, resData);
              let param = { oneLevelCount, oneLevelData };
              resolve(param);
            } else {
              reject(result.message);
            }
          },
        });
      });
    }
    // 二级目录：展示其他文件夹
    /**
     *
     * @param {String} proID 项目ID
     * @param {String} proType 项目类型
     * @returns
     */
    function handleTwoLevelList(proID, proType) {
      return new Promise((resolve, reject) => {
        $.ajax({
          async: false,
          url: base_url + "/projectManage/queryProCateByProID",
          headers: {
            Accept: "application/json; charset=utf-8",
            Authorization: layui.sessionData("userToken").key,
          },
          method: "post",
          contentType: "application/json",
          data: JSON.stringify({ proID, proType }),
          dataType: "json",
          success: function (result) {
            if (result.code == "200") {
              console.log(result);
              twoLevelData = result.data.project.length
                ? result.data.project
                : [];
              resolve(twoLevelData);
            } else {
              reject(result.message);
            }
          },
        });
      });
    }

    // // //同步加载文件的数据
    // function renderProduct(page, limit, startTime, endTime, projectName) {
    //   $.ajax({
    //     async: false,
    //     url: base_url + "/projectManage/queryProListByProperty",
    //     headers: {
    //       Accept: "application/json; charset=utf-8",
    //       Authorization: layui.sessionData("userToken").key,
    //     },
    //     method: "post",
    //     contentType: "application/json",
    //     data: JSON.stringify({
    //       limit,
    //       page,
    //       sort: "1",
    //     }),
    //     dataType: "json",
    //     success: function (result) {
    //       debugger;
    //       resCount = result.data.projectList.total;
    //       resData = result.data.projectList.list;
    //       renderProductHtml(resData);
    //     },
    //   });
    // }
    //同步加载文件的数据
    var startTime = "",
      endTime = "",
      projectName = "";
    function renderProduct1(page, limit, startTime, endTime, projectName) {
      loadIndex = layer.load(2);
      $.ajax({
        async: false,
        url: base_url + "/projectManage/queryProListByProperty",
        headers: {
          Accept: "application/json; charset=utf-8",
          Authorization: layui.sessionData("userToken").key,
        },
        method: "post",
        contentType: "application/json",
        data: JSON.stringify({
          limit,
          page,
          sort: "1",
          startTime,
          endTime,
          projectName,
        }),
        dataType: "json",
        success: function (result) {
          resCount = result.data.projectList.total;
          resData = result.data.projectList.list;
          renderProductHtml(resData);
        },
      });
    }
    //分页的完整功能
    function renderPage1() {
      renderProduct1(page, limit, startTime, endTime, projectName);
      laypage.render({
        elem: "layuipage",
        count: resCount,
        limit: limit,
        limits: [limit],
        curr: page,
        theme: "#334d80",
        layout: ["prev", "page", "next", "skip", "count", "limit"],
        prev: '<i class="layui-icon"></i>',
        next: '<i class="layui-icon"></i>',
        jump: function (obj, first) {
          console.info(obj);
          page = obj.curr;
          if (!first) {
            renderProduct1(page, limit, startTime, endTime, projectName);
          }
        },
      });
    }
    layui.sessionData("isSwitch", {
      key: "key",
      value: true,
    });
    $(".switchContentBtn").click(function () {
      if (layui.sessionData("isSwitch").key) {
        $(".projectManagementTable").show();
        $(".projectManagementList").hide();
        layui.sessionData("isSwitch", {
          key: "key",
          value: false,
        });
      } else {
        $(".projectManagementTable").hide();
        $(".projectManagementList").show();
        layui.sessionData("isSwitch", {
          key: "key",
          value: true,
        });
      }
    });

    exports("projectManagement", {});
  }
);
